package com.xjw.adapte {
	import com.xjw.ArrayHelp;
	import flash.display.Stage;
	import flash.events.Event;

	/**
	 * 自适应管理和注册类
	 * @author pethan
	 *
	 */
	public class AdapteManager {
		private static var _instance:AdapteManager;
		private var _stage:Stage;
		private var adaptes:Vector.<IAdapte>;

		/**
		 * 设置Stage 用来侦听Stage发生改变
		 * @param _stage
		 *
		 */
		public function setStage(_stage:Stage):void {
			this._stage = _stage;
			this._stage.addEventListener(Event.RESIZE, onResize);
		}

		//Stage大小发生改变时,调用
		private function onResize(event:Event):void {
			this.adaptes.forEach(callResize);
		}

		//每项进行调用.
		private function callResize(idapte:IAdapte, index:int, iadaptes:Vector.<IAdapte>):void {
			idapte.adapte(_stage.stageWidth, _stage.stageHeight);
		}

		public static function getInstance():AdapteManager {
			if (_instance == null){
				_instance = new AdapteManager(new SingleStnace());
			}
			return _instance;
		}

		public function AdapteManager(se:SingleStnace){
			if (se == null){
				throw new Error('请使用单例');
			}
			adaptes = new Vector.<IAdapte>();
		}

		/**
		 * 添加需要被Stage发生改变要调用的Idapte
		 * @param iadape
		 *
		 */
		public function addAdpateControl(iadapte:IAdapte):void {
			if (this._stage == null){
				throw new Error('请添加Stage');
			}
			if (this.adaptes.indexOf(iadapte) == -1){
				this.adaptes.push(iadapte);
				this.toAddapte(iadapte);
				iadapte.adapte(_stage.stageWidth, _stage.stageHeight);
			}
		}

		/**
		 * 移除自适应大小
		 * @param idapte
		 *
		 */
		public function removeAdapteControl(idapte:IAdapte):void {
			if (this.adaptes.indexOf(idapte) != -1){
				ArrayHelp.deleteContent(adaptes, idapte);
			}
		}

		/**
		 * 立即重新部局下 (先验证,是否有存此apdate,如果不存在就报错)
		 * @param idapte
		 *
		 */
		public function adapteNow(idapte:IAdapte):void {
			if (this.adaptes.indexOf(idapte) == -1){
				throw new Error('对不起,此adapte没有添加到控件中心');
			}
			this.toAddapte(idapte);
		}

		/**
		 * 重新更新所有的部局
		 *
		 */
		public function adateAllNow():void {
			this.adaptes.forEach(callResize);
		}

		//调用排序
		private function toAddapte(idapte:IAdapte):void {
			idapte.adapte(this._stage.stageWidth, this._stage.stageHeight);
		}
	}
}

class SingleStnace {
}